package com.ouheng.shop.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ouheng.shop.dao.ArticleImageDao;
import com.ouheng.shop.dao.CmsDao;
import com.ouheng.shop.domain.ArticleImageDO;
import com.ouheng.shop.domain.CmsDO;
import com.ouheng.shop.service.CmsService;



@Service
public class CmsServiceImpl implements CmsService {
	@Autowired
	private CmsDao cmsDao;
	
	@Autowired
	private ArticleImageDao articleImageDao;
	
	@Override
	public CmsDO get(Long id){
		return cmsDao.get(id);
	}
	
	@Override
	public List<CmsDO> list(Map<String, Object> map){
		return cmsDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return cmsDao.count(map);
	}
	
	@Override
	@Transactional
	public int save(CmsDO cms){
		return cmsDao.save(cms);
	}
	
	@Override
	@Transactional
	public int update(CmsDO cms){
		return cmsDao.update(cms);
	}
	
	@Override
	@Transactional
	public int remove(Long id){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cmsid", id);
		List<ArticleImageDO> listimage = articleImageDao.list(map);
		for (ArticleImageDO articleImageDO : listimage) {
			articleImageDao.remove(articleImageDO.getId());
		}
		return cmsDao.remove(id);
	}
	
	@Override
	@Transactional
	public int batchRemove(Long[] ids){
		for (Long long1 : ids) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("cmsid", long1);
			List<ArticleImageDO> listimage = articleImageDao.list(map);
			for (ArticleImageDO articleImageDO : listimage) {
				articleImageDao.remove(articleImageDO.getId());
			}
		}
		return cmsDao.batchRemove(ids);
	}

	@Override
	@Transactional
	public void saveImage(CmsDO cms, List<Object> list) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cmsid", cms.getId());
		List<ArticleImageDO> listimage = articleImageDao.list(map);
		for (ArticleImageDO articleImageDO : listimage) {
			articleImageDao.remove(articleImageDO.getId());
		}
		if (!list.isEmpty()) {
            for (Object obj : list) {
                if (obj != null) {
                	ArticleImageDO articleImageDO = (ArticleImageDO) obj;
                    if (com.ouheng.common.utils.StringUtils.isNoneBlank(articleImageDO.getSource())) {
                    	articleImageDO.setCmsid(cms.getId());
                    	articleImageDO.setLarge(articleImageDO.getSource());
                    	articleImageDO.setSource(articleImageDO.getSource());
                    	articleImageDO.setMedium(articleImageDO.getSource());
                    	articleImageDO.setThumbnail(articleImageDO.getSource());
                    	articleImageDao.save(articleImageDO);
                    }
                }
            }
        }
	}
	
}
